import dayjs from "dayjs"
import storage from "@/utils/storage.js"
const ServerUUID = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
const CharacteristicsNotify = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E'
const CharacteristicsWrite = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E'
// 关闭蓝牙服务连接
export const closeDevice = (deviceId) => {
	uni.closeBLEConnection({
		deviceId: deviceId,
		success(res) {
			console.log('closeBLEConnection', res)
		}
	})
}
// 初始化蓝牙
export const InitBlueTooth = (tip) => {
	let device = storage.getCurrentDevice()
	if (device) {
		closeDevice(device.deviceId)
	}
	return new Promise((resolve, reject) => {
		uni.openBluetoothAdapter({
			success: (res) => { //已打开
				uni.getBluetoothAdapterState({ //蓝牙的匹配状态
					success: (row) => {
						resolve(row)
					},
					fail(error) {
						reject(error)
						console.log("未打开蓝牙1")
						if (tip) {
							uni.showToast({
								icon: 'none',
								title: '请打开本机蓝牙设备'
							});
						}
					}
				});
			},
			fail: err => { //未打开
				reject(err)
				console.log("未打开蓝牙2111")
				if (tip) {
					uni.showToast({
						icon: 'none',
						title: '请打开本机蓝牙设备'
					});
				}
			}
		})
	})
}
export const CreateBlueToothConnection = (device) => {
	return new Promise((resolve, reject) => {
		let createBLEConnection = (device) => {
			uni.createBLEConnection({
				// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
				deviceId: device.deviceId,
				success(res) {
					console.log("连接成功：" + JSON.stringify(res))
					let port = uni.getSystemInfoSync().platform
					switch (port) {
						case 'ios':
							getBLEDeviceServices(device)
							break;
						default:
							setMaxMTU(device)
							break;
					}
				},
				fail(res) {
					if (res.errCode !== -1) {
						closeDevice(device)
						reject(res)
					}
					console.log("连接失败：" + JSON.stringify(res))
					if (JSON.stringify(res).indexOf("already connect") > -1) {
						closeDevice(device)
					}
				}
			})
		}
		// 设置最大MTU值 (可以参照文档)
		let setMaxMTU = (device) => {
			console.log(11111)
			uni.setBLEMTU({
				deviceId: device.deviceId,
				mtu: 200,
				success(res) {
					console.log("设置最大值成功")
					getBLEDeviceServices(device)
				},
				fail(res) {
					closeDevice(device)
					reject(res)
					console.log('设置最大MTU值失败', res)
					uni.showToast({
						icon: 'none',
						title: '设备初始化失败'
					})
				}
			})
		}
		// 获取蓝牙设备所有服务
		let getBLEDeviceServices = (device) => {
			console.log(22222222)
			setTimeout(() => {
				uni.getBLEDeviceServices({
					deviceId: device.deviceId,
					success(res) {
						console.log("获取服务成功：" + JSON.stringify(res))
						let server = res.services.find(service => {
							return service.uuid === ServerUUID
						})
						if (server) {
							getBLEDeviceCharacteristics(device, server)
						} else {
							closeDevice(device)
							reject(res)
						}
					},
					fail(res) {
						reject(res)
						console.log("获取服务失败：" + JSON.stringify(res))
						closeDevice(device)
					}
				})
			}, 10000)
		}
		// 根据服务uuid和deviceid获取特征值
		let getBLEDeviceCharacteristics = (decive, service) => {
			uni.getBLEDeviceCharacteristics({
				// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
				deviceId: decive.deviceId,
				// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
				serviceId: service.uuid,
				success(res) {
					console.log("获取特征值成功：", res)
					res.characteristics.map(c => {
						if (c.properties.notify || c.properties.indicate) {
							notifyBLECharacteristicValueChange(decive, service, c)
						}
					})
				},
				fail(res) {
					console.log("获取特征值失败：", res)
					closeDevice(device)
					reject(res)
				}
			})
		}
		let notifyBLECharacteristicValueChange = (decive, service, c) => {
			uni.notifyBLECharacteristicValueChange({
				state: true, // 启用 notify 功能
				// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
				deviceId: decive.deviceId,
				// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
				serviceId: service.uuid,
				// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
				characteristicId: c.uuid,
				success(res) {
					console.log('启用低功耗蓝牙设备特征值变化时的 notify 功能成功')
					console.log(resolve)
					resolve({
						device,
						service,
						c
					})
				},
				fail(res) {
					closeDevice(device)
					reject(res)
					uni.showToast({
						title: '连接蓝牙失败',
						icon: 'none'
					})
					console.log("启用低功耗蓝牙设备特征值变化时的 notify 功能失败：" + JSON.stringify(res))
				}
			})
		}
		createBLEConnection(device)
	})

}
export const OnBlueTooth = () => {

}
// 读取低功耗蓝牙设备的特征值的二进制数据值
export const ReadBlueTooth = (decive, service, characteristics) => {
	if (characteristics.properties.read) {
		uni.readBLECharacteristicValue({
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			deviceId: decive.deviceId,
			// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
			serviceId: service.uuid,
			// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
			characteristicId: characteristics.uuid,
			success(res) {
				console.log('读取成功:', res, {
					deviceId: decive.deviceId,
					serviceId: service.uuid,
					characteristicId: characteristics.uuid
				})
			},
			fail(res) {
				console.log('读取失败:', res, {
					deviceId: decive.deviceId,
					serviceId: service.uuid,
					characteristicId: characteristics.uuid
				})
			}
		})
	}
}
